﻿<%@ WebHandler Language="C#" Class="SellOfferAdd" %>

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using XBase.Common;
using XBase.Business.Office.SellManager;
using XBase.Business.Common;
using XBase.Model.Office.SellManager;
using System.Collections;

public class SellOfferAdd : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
        bool isSucc = false;//是否更新成功     
        string strMsg = string.Empty;//操作返回的信息  
        string strCode = string.Empty;
        int orderID = 0;
        string action = context.Request.Params["action"].ToString().Trim();	//动作
        string CodeType = context.Request.Params["CodeType"].ToString().Trim();	//报价单编号产生的规则                                    
        string OfferNo = context.Request.Params["OfferNo"].ToString().Trim();	//报价单编号

        //获取扩展属性
        Hashtable ht = GetExtAttr(context);
        
        //状态为insert时才计算编号
        if (action == "insert") 
        {
            //如果编码规则不为空，表示自动产生编号
            if (CodeType.Length != 0)
            {
                strCode = ItemCodingRuleBus.GetCodeValue(CodeType, "SellOffer", "OfferNo");
            }
            else
            {
                strCode = OfferNo;
            }
            /*判断是否存在*/
            bool isAlready = PrimekeyVerifyBus.CheckCodeUniq("SellOffer", "OfferNo", strCode);
            if (!isAlready || string.IsNullOrEmpty(strCode))
            {
                if (string.IsNullOrEmpty(strCode))
                {
                    strMsg = "该单据编号规则自动生成的序号已经达到上限，请检查编号规则设置!";
                }
                else
                {
                    strMsg = "销售报价单据编号已经存在";
                }
            }
            else
            {
                SellOfferModel sellOfferModel = GetOrderModel(strCode, context);
                List<SellOfferDetailModel> sellOfferDetailModelList = GetOrderDetailModelList(strCode, context);
                List<SellOfferHistoryModel> sellOfferHistoryModelList = GetSellOfferHistoryModelList(strCode, context);
                isSucc = SellOfferBus.InsertOrder(ht, sellOfferModel, sellOfferDetailModelList, sellOfferHistoryModelList, out strMsg);
            }
        }
        else if (action == "update")//保存后修改
        {
            strCode = OfferNo;
            SellOfferModel sellOfferModel = GetOrderModel(strCode, context);
            List<SellOfferDetailModel> sellOfferDetailModelList = GetOrderDetailModelList(strCode, context);
            List<SellOfferHistoryModel> sellOfferHistoryModelList = GetSellOfferHistoryModelList(strCode, context);
            isSucc = SellOfferBus.UpdateOrder(ht,sellOfferModel, sellOfferDetailModelList, sellOfferHistoryModelList, out strMsg);
        }
        else if (action == "again")//再次报价
        {
            strCode = OfferNo;
            string strStatus = context.Request.Params["status"].ToString().Trim();	//动作
            SellOfferModel sellOfferModel = GetOrderModel(strCode, context);
            sellOfferModel.QuoteTime = sellOfferModel.QuoteTime + 1;
            sellOfferModel.BillStatus = strStatus;
            List<SellOfferDetailModel> sellOfferDetailModelList = GetOrderDetailModelList(strCode, context);
            List<SellOfferHistoryModel> sellOfferHistoryModelList = GetSellOfferHistoryModelList(strCode, context);
            foreach (SellOfferHistoryModel model in sellOfferHistoryModelList)
            {
                model.OfferTime = model.OfferTime + 1;
            }
            isSucc = SellOfferBus.UpdateOrder(ht,sellOfferModel, sellOfferDetailModelList, sellOfferHistoryModelList, out strMsg);
            if (isSucc)
            {
                strMsg = "再次报价成功！";
            }
            else
            {
                strMsg = "再次报价失败，请联系系统管理员！";
            }
        }
        else if (action == "UnConfirm")//取消确认
        {
            strCode = OfferNo;
            isSucc = SellOfferBus.UnConfirmOrder(strCode, out strMsg);
        }
        else if (action == "confirm")//确认
        {
            strCode = OfferNo;
            isSucc = SellOfferBus.ConfirmOrder(strCode, out strMsg);
        }

        else if (action == "close")//结单
        {
            strCode = OfferNo;
            isSucc = SellOfferBus.CloseOrder(strCode, out strMsg);
        }
        else if (action == "unClose")//取消结单
        {
            strCode = OfferNo;
            isSucc = SellOfferBus.UnCloseOrder(strCode, out strMsg);
        }
        JsonClass jc;
        if (isSucc)
        {
            orderID = SellOfferBus.GetOrderID(strCode);
            jc = new JsonClass(orderID, "", strCode, strMsg, 1);
        }
        else
        {
            jc = new JsonClass(orderID, "", strCode, strMsg, 0);
        }
        context.Response.Write(jc.ToJosnString());
    }

    /// <summary>
    /// 获取扩展属性值
    /// </summary>
    /// <returns></returns>
    private Hashtable GetExtAttr(HttpContext context)
    {
        try
        {
            Hashtable ht = new Hashtable();
            //string strKeyList = GetParam("keyList").Trim();
            string strKeyList = context.Request.Params["keyList"].ToString().Trim();
            string[] arrKey = strKeyList.Split('|');
            //取得扩展属性值
            for (int y = 0; y < arrKey.Length; y++)
            {
                //不为空的字段名才取值
                if (arrKey[y].Trim().Length != 0)
                {
                    ht.Add(arrKey[y].Trim(), context.Request.Params[arrKey[y].Trim()].Trim());//添加keyvalue键值对
                }
            }
            return ht;
        }
        catch (Exception)
        { return null; }
    }

    /// <summary>
    /// 获取SellOfferModel表实体
    /// </summary>
    /// <param name="strCode"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    private SellOfferModel GetOrderModel(string strCode, HttpContext context)
    {
        SellOfferModel sellOfferModel = new SellOfferModel();
        string CustID = context.Request.Params["CustID"].ToString().Trim();
        string CustTel = context.Request.Params["CustTel"].ToString().Trim();
        string FromType = context.Request.Params["FromType"].ToString().Trim();
        string FromBillID = context.Request.Params["FromBillID"].ToString().Trim();
        string Title = context.Request.Params["Title"].ToString().Trim();
        string PayType = context.Request.Params["PayType"].ToString().Trim();
        string Seller = context.Request.Params["Seller"].ToString().Trim();
        string SellDeptId = context.Request.Params["SellDeptId"].ToString().Trim();
        string MoneyType = context.Request.Params["MoneyType"].ToString().Trim();
        string TakeType = context.Request.Params["TakeType"].ToString().Trim();
        string CarryType = context.Request.Params["CarryType"].ToString().Trim();
        string SellType = context.Request.Params["SellType"].ToString().Trim();
        string BusiType = context.Request.Params["BusiType"].ToString().Trim();
        string ExpireDate = context.Request.Params["ExpireDate"].ToString().Trim();
        string TotalPrice = context.Request.Params["TotalPrice"].ToString().Trim();
        string TotalTax = context.Request.Params["TotalTax"].ToString().Trim();
        string TotalFee = context.Request.Params["TotalFee"].ToString().Trim();
        string Discount = context.Request.Params["Discount"].ToString().Trim();
        string DiscountTotal = context.Request.Params["DiscountTotal"].ToString().Trim();
        string RealTotal = context.Request.Params["RealTotal"].ToString().Trim();
        string CountTotal = context.Request.Params["CountTotal"].ToString().Trim();
        string CurrencyType = context.Request.Params["CurrencyType"].ToString().Trim();
        string Rate = context.Request.Params["Rate"].ToString().Trim();
        string QuoteTime = context.Request.Params["QuoteTime"].ToString().Trim();
        string OfferDate = context.Request.Params["OfferDate"].ToString().Trim();
        string PayRemark = context.Request.Params["PayRemark"].ToString().Trim();
        string DeliverRemark = context.Request.Params["DeliverRemark"].ToString().Trim();
        string PackTransit = context.Request.Params["PackTransit"].ToString().Trim();
        string isAddTax = context.Request.Params["isAddTax"].ToString().Trim();
        string Remark = context.Request.Params["Remark"].ToString().Trim();
        string strCanViewUser = context.Request.Params["CanViewUser"].ToString().Trim();//可查看人员
        string CanViewUser = strCanViewUser.Length == 0 ? null : strCanViewUser;
        sellOfferModel.CanViewUser = CanViewUser;
        
        sellOfferModel.OfferNo = strCode;
        try
        {
            sellOfferModel.CustID = Convert.ToInt32(CustID);
        }
        catch
        { }
        sellOfferModel.CustTel = CustTel;

        sellOfferModel.FromType = FromType;
        try
        {
            sellOfferModel.FromBillID = Convert.ToInt32(FromBillID);
        }
        catch { }

        sellOfferModel.Title = Title;
        try
        {
            sellOfferModel.PayType = Convert.ToInt32(PayType);
        }
        catch { }
        try
        {
            sellOfferModel.Seller = Convert.ToInt32(Seller);
        }
        catch { }
        try
        {
            sellOfferModel.SellDeptId = Convert.ToInt32(SellDeptId);
        }
        catch { }
        try
        {
            sellOfferModel.MoneyType = Convert.ToInt32(MoneyType);
        }
        catch { }
        try
        {
            sellOfferModel.TakeType = Convert.ToInt32(TakeType);
        }
        catch { }
        try
        {
            sellOfferModel.CarryType = Convert.ToInt32(CarryType);
        }
        catch { }

        try
        {
            sellOfferModel.SellType = Convert.ToInt32(SellType);
        }
        catch { }

        sellOfferModel.BusiType = BusiType;
        sellOfferModel.ExpireDate = Convert.ToDateTime(ExpireDate);
        sellOfferModel.TotalPrice = Convert.ToDecimal(TotalPrice.Length == 0 ? "0" : TotalPrice);
        sellOfferModel.TotalTax = Convert.ToDecimal(TotalTax.Length == 0 ? "0" : TotalTax);
        sellOfferModel.TotalFee = Convert.ToDecimal(TotalFee.Length == 0 ? "0" : TotalFee);
        sellOfferModel.Discount = Convert.ToDecimal(Discount.Length == 0 ? "0" : Discount);
        sellOfferModel.DiscountTotal = Convert.ToDecimal(DiscountTotal.Length == 0 ? "0" : DiscountTotal);
        sellOfferModel.RealTotal = Convert.ToDecimal(RealTotal.Length == 0 ? "0" : RealTotal);
        sellOfferModel.CountTotal = Convert.ToDecimal(CountTotal.Length == 0 ? "0" : CountTotal);
        try
        {
            sellOfferModel.CurrencyType = Convert.ToInt32(CurrencyType);
        }
        catch { }
        sellOfferModel.Rate = Convert.ToDecimal(Rate);
        try
        {
            sellOfferModel.QuoteTime = Convert.ToInt32(QuoteTime);
        }
        catch { }
        sellOfferModel.OfferDate = Convert.ToDateTime(OfferDate);
        sellOfferModel.PayRemark = PayRemark;
        sellOfferModel.DeliverRemark = DeliverRemark;
        sellOfferModel.PackTransit = PackTransit;
        sellOfferModel.isAddTax = isAddTax;
        sellOfferModel.Remark = Remark;
        sellOfferModel.BillStatus = "1";
        sellOfferModel.CreateDate = DateTime.Now;
        sellOfferModel.ModifiedDate = DateTime.Now;
        
            sellOfferModel.Creator = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).EmployeeID;//制单人ID                                                
            sellOfferModel.ModifiedUserID = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).UserID; ;//最后更新用户ID(对应操作用户UserID)                      
            sellOfferModel.CompanyCD = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).CompanyCD;//公司代码  
       

        return sellOfferModel;
    }


    /// <summary>
    /// 获取SellOfferDetailModel表实体列表
    /// </summary>
    /// <param name="strCode"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    private List<SellOfferDetailModel> GetOrderDetailModelList(string strCode, HttpContext context)
    {
        string[] strarray = null;
        string recorditems = "";
        string[] inseritems = null;
        string strfitinfo = context.Request.Params["strfitinfo"].ToString().Trim();

        SellOfferDetailModel sellOfferDetailModel;
        List<SellOfferDetailModel> sellOfferDetailModelList = new List<SellOfferDetailModel>();

        strarray = strfitinfo.Split('|');
        string[] sqlarray = new string[strarray.Length];

        for (int i = 0; i < strarray.Length; i++)
        {
            StringBuilder fitsql = new StringBuilder();
            recorditems = strarray[i];
            inseritems = recorditems.Split(',');
            if (recorditems.Length != 0)
            {
                sellOfferDetailModel = new SellOfferDetailModel();
                sellOfferDetailModel.OfferNo = strCode;
                sellOfferDetailModel.SortNo = Convert.ToInt32(inseritems[0].ToString());
                sellOfferDetailModel.ProductID = Convert.ToInt32(inseritems[1].ToString());
                sellOfferDetailModel.ProductCount = Convert.ToDecimal(inseritems[2].ToString());
                sellOfferDetailModel.UnitID = Convert.ToInt32(inseritems[3].ToString());
                sellOfferDetailModel.UnitPrice = Convert.ToDecimal(inseritems[4].ToString());
                sellOfferDetailModel.TaxPrice = Convert.ToDecimal(inseritems[5].ToString());
                sellOfferDetailModel.Discount = Convert.ToDecimal(inseritems[6].ToString());
                sellOfferDetailModel.TaxRate = Convert.ToDecimal(inseritems[7].ToString());
                sellOfferDetailModel.TotalFee = Convert.ToDecimal(inseritems[8].ToString());
                sellOfferDetailModel.TotalPrice = Convert.ToDecimal(inseritems[9].ToString());
                sellOfferDetailModel.TotalTax = Convert.ToDecimal(inseritems[10].ToString());
                sellOfferDetailModel.SendTime = Convert.ToInt32(inseritems[11].ToString());
                //sellOfferDetailModel.Package = inseritems[12].ToString();
                sellOfferDetailModel.Remark = inseritems[13].ToString();

                if (inseritems[12].ToString().Trim().Length != 0)
                {
                    sellOfferDetailModel.Package = Convert.ToInt32(inseritems[12].ToString());
                }
                //string UsedUnitID = context.Request.Params["UsedUnitID"].ToString().Trim();
                //string UsedUnitCount = context.Request.Params["UsedUnitCount"].ToString().Trim();
                //string UsedPrice = context.Request.Params["UsedPrice"].ToString().Trim();
                //string ExRate = context.Request.Params["ExRate"].ToString().Trim();
                sellOfferDetailModel.UsedUnitID = Convert.ToInt32(inseritems[14].ToString());//单位
                sellOfferDetailModel.UsedUnitCount = Convert.ToDecimal(inseritems[15].ToString());//数量
                sellOfferDetailModel.UsedPrice = Convert.ToDecimal(inseritems[16].ToString());//单价
                sellOfferDetailModel.ExRate = Convert.ToDecimal(inseritems[17].ToString());//换算率

                sellOfferDetailModel.CompanyCD = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).CompanyCD;//单位编码               
               
                sellOfferDetailModelList.Add(sellOfferDetailModel);
            }
        }

        return sellOfferDetailModelList;
    }

    /// <summary>
    /// 获取表SellOfferHistoryModel实体列表
    /// </summary>
    /// <param name="strCode"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    private List<SellOfferHistoryModel> GetSellOfferHistoryModelList(string strCode, HttpContext context)
    {
        SellOfferHistoryModel sellOfferHistoryModel;
        List<SellOfferHistoryModel> sellOfferHistoryModelList = new List<SellOfferHistoryModel>();

        List<SellOfferDetailModel> sellOfferDetailModelList = GetOrderDetailModelList(strCode, context);

        foreach (SellOfferDetailModel sellOfferDetailModel in sellOfferDetailModelList)
        {
            sellOfferHistoryModel = new SellOfferHistoryModel();
            sellOfferHistoryModel.OfferNo = strCode;
            sellOfferHistoryModel.OfferTime = Convert.ToInt32(context.Request.Params["QuoteTime"].ToString().Trim());
            sellOfferHistoryModel.ProductID = sellOfferDetailModel.ProductID;
            
                sellOfferHistoryModel.Seller = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).EmployeeID;//业务员  
                sellOfferHistoryModel.CompanyCD = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).CompanyCD;//单位编码             
          
            sellOfferHistoryModel.TotalPrice = sellOfferDetailModel.TotalFee;
            sellOfferHistoryModel.OfferDate = Convert.ToDateTime(context.Request.Params["OfferDate"].ToString().Trim());

            sellOfferHistoryModelList.Add(sellOfferHistoryModel);

        }
        sellOfferHistoryModel = new SellOfferHistoryModel();
        sellOfferHistoryModel.OfferNo = strCode;
        sellOfferHistoryModel.OfferTime = Convert.ToInt32(context.Request.Params["QuoteTime"].ToString().Trim());
        string RealTotal = context.Request.Params["RealTotal"].ToString().Trim();
        sellOfferHistoryModel.TotalPrice = Convert.ToDecimal(RealTotal);
        
            sellOfferHistoryModel.Seller = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).EmployeeID;//业务员  
            sellOfferHistoryModel.CompanyCD = ((UserInfoUtil)SessionUtil.Session["UserInfo"]).CompanyCD;//单位编码             
       
        sellOfferHistoryModel.OfferDate = Convert.ToDateTime(context.Request.Params["OfferDate"].ToString().Trim());
        sellOfferHistoryModelList.Add(sellOfferHistoryModel);
        return sellOfferHistoryModelList;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}